"""
rqalpha可视化的utils包
"""
import pandas as pd
import datetime as dt
from highcharts import Highstock


class rqplot(object):
    # 传入rqalpha的result
    def __init__(self, result):
        self.result = result

    
    @staticmethod
    def _backtest_json(strategy, benchmark):
        # 均为带dateindex(str)的数据
        # 净值的时间序列数据
        dd = pd.concat([strategy, benchmark], axis=1)
        dd.index = [(int(dt.datetime.timestamp(x)) ) * 1000 for x in pd.to_datetime(dd.index)]
        return dd.iloc[:, 0].reset_index().values.tolist(), dd.iloc[:, 1].reset_index().values.tolist()
    

    @staticmethod
    def _alpha_json(strategy, benchmark):
        # 均为带dateindex(str)的数据
        # 净值的时间序列数据
        alpha = strategy.pct_change() - benchmark.pct_change()
        alpha = (alpha + 1.0).cumprod()
        alpha.index = [(int(dt.datetime.timestamp(x)) ) * 1000 for x in pd.to_datetime(alpha.index)]
        alpha = alpha * 100 - 100
        return alpha.reset_index().values.tolist()

    def backtest_plot(self):
        strategy, benchmark = self._backtest_json(self.result['sys_analyser']['portfolio']['unit_net_value'],
                    self.result['sys_analyser']['benchmark_portfolio']['unit_net_value'])

        h = Highstock()

        h.add_data_set(strategy, 'line', 'strategy',)
        h.add_data_set(benchmark, 'line', 'benchmark')

        options = {
            'title':{
            'text': '回测结果',  
            },
            'rangeSelector': {
                                'selected': 4
                            },
                            'yAxis': {
                                'labels': {
                                    'formatter': "function () {\
                                        return (this.value > 0 ? ' + ' : '') + this.value + '%';\
                                    }"
                                },
                                'plotLines': [{
                                    'value': 0,
                                    'width': 2,
                                    'color': 'silver'
                                }]
                            },
                            'plotOptions': {
                                'series': {
                                    'compare': 'percent',
                                }
                            },
                            'tooltip': {
                                'pointFormat': '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
                                'valueDecimals': 2
                            },
        }

        h.set_dict_options(options)
        return h


    def alpha_plot(self):
        alpha = self._alpha_json(self.result['sys_analyser']['portfolio']['unit_net_value'],
                                    self.result['sys_analyser']['benchmark_portfolio']['unit_net_value'])
        h = Highstock()

        h.add_data_set(alpha, 'line', 'alpha')
        options = {
            'title':{
            'text': '超额收益',  
            },
            'rangeSelector': {
                                'selected': 4
                            },
                            'yAxis': {
                                'labels': {
                                    'formatter': "function () {\
                                        return (this.value > 0 ? ' + ' : '') + this.value + '%';\
                                    }"
                                },
                                'plotLines': [{
                                    'value': 0,
                                    'width': 2,
                                    'color': 'silver'
                                }]
                            },
                            'plotOptions': {
                                'series': {
                                    'compare': 'value',
                                }
                            },
                            'tooltip': {
                                'pointFormat': '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}%</b> ({point.change}%)<br/>',
                                'valueDecimals': 2
                            },
        }

        h.set_dict_options(options)

        return h